import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 30000 // 上传文件需要更长的超时时间
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 1 || res.code === 0 || res.code === 200) {
      return res
    }
    
    ElMessage.error(res.msg || '请求失败')
    return Promise.reject(new Error(res.msg || '请求失败'))
  },
  error => {
    const msg = error.response?.data?.msg || error.message || '网络请求失败'
    ElMessage.error(msg)
    
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      location.href = '/login'
    }
    
    return Promise.reject(error)
  }
)

/**
 * 通用功能API
 */
export default {
  /**
   * 文件上传
   * @param {File} file 文件对象
   * @returns {Promise} 返回上传结果
   */
  upload(file) {
    const formData = new FormData()
    formData.append('file', file)
    
    return request({
      url: '/admin/common/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
} 